#
# from oncall.models import OncallInfo
# from rest_framework.views import APIView
# from rest_framework.response import Response
# from rest_framework import status
# from rest_framework import serializers
# from rest_framework.filters import SearchFilter, OrderingFilter
# from django_filters.rest_framework import DjangoFilterBackend
from CassTimeDevOps.basic import BaseModelViewSet
import datetime

from django.shortcuts import render
from rest_framework import viewsets, status
from oncall.models import OncallInfo
from oncall.filters import OncallInfoFilter
from oncall.serializers import OncallInfoSerializer
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend

from common.custom import CommonPagination
"""以下是使用Viewset的视图"""

class OncallerViewset(BaseModelViewSet):
    """
    根据开始结束日期查询url:http://127.0.0.1:8000/oncaller/?start_time=2020-08-02&end_time=2021-08-02
    根据开始查询url:http://127.0.0.1:8000/oncaller/?start_time=2020-08-02
    根据组查询url:http://127.0.0.1:8000/oncaller/?dev_group=4
    """
    filter_class = OncallInfoFilter
    queryset = OncallInfo.objects.all()
    serializer_class = OncallInfoSerializer
    pagination_class = CommonPagination
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    filter_fields = ("dev_group",)

    def get_queryset(self):
        plan_id = self.request.GET.get('plan_id', None)
        if plan_id:
            self.queryset = self.queryset.filter(deploy_plan_id=plan_id)
            return self.queryset.all()
        return self.queryset.all()

    def list(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        user_id = request.user.id
        request.data["creator"] = user_id
        oc_dev = request.data["dev_group"]
        oc_name = request.data["oncaller"]
        oc_sta = request.data["start_time"]
        oc_end = request.data["end_time"]
        oc_dict={
           "dev_group":oc_dev,                              # "dev_name":OncallInfoSerializer.get_dev_name(dev_group=oc_dev),
           "oncaller":oc_name,
           "start_time":oc_sta,
           "end_time":oc_end
        }

        serializer = self.get_serializer(data=oc_dict)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        results = dict()
        results["code"] = status.HTTP_201_CREATED
        results["data"] = serializer.data
        results["msg"] = "创建成功"
        results["success"] = True
        return Response(results, status=status.HTTP_201_CREATED, headers=headers)

    def retrieve(self, request, *args, **kwargs):
        oc_dev = request.data["dev_group"]   #获取前端需要查询的限定数据
        instance = OncallInfo.objects.get(dev_group=oc_dev)   #获取数据
        serializer = self.get_serializer(instance)            #实例化数据
        results = dict()
        results["code"] = status.HTTP_200_OK
        results["data"] = serializer.data
        results["msg"] = "检索成功"
        results["success"] = True
        return Response(results, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        user_id = request.user.id
        request.data["editor"] = user_id
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        results = dict()
        results["code"] = status.HTTP_200_OK
        results["data"] = serializer.data
        results["msg"] = "更新成功"
        results["success"] = True
        return Response(results, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if hasattr(instance, 'is_delete'):
            instance.is_delete = 1
            instance.save()
        else:
            instance.delete()
        results = dict()
        results["code"] = status.HTTP_204_NO_CONTENT
        results["data"] = ""
        results["msg"] = "删除成功"
        results["success"] = True
        return Response(results)


    @action(methods=['GET', 'POST'], detail=False)
    def get_today(self, request):
        """
        获取当天排班，默认是获取所有排班
        url:http://127.0.0.1:8000/oncaller/get_today/
        :param request:
        :return:
        """
        queryset = OncallInfo.objects.filter(start_time__gte=datetime.datetime.now().date())
        print(queryset.query)
        serializer = OncallInfoSerializer(queryset, many=True)

        return Response(serializer.data)
    # def list(self, request):
    #     queryset = models.OncallInfo.objects.all()
    #     serializer = OncallInfoSerializer(queryset, many=True)
    #
    #     return Response(serializer.data)
    #
    # def retrieve(self, request, pk=None):
    #     queryset = models.OncallInfo.objects
    #     oncaller = get_object_or_404(queryset, pk=pk)
    #     serializer = OncallInfoSerializer(oncaller)
    #     return Response(serializer.data)


